//可否下拉
var is_bool=true;
// 页码信息
var page_no=1;



$(function() {
    //浏览记录添加
    addBrowse();

    getTopicCommentsList();

    $(window).scroll(function(){
    　　var scrollTop = $(this).scrollTop();
    　　var scrollHeight = $(document).height();
    　　var windowHeight = $(this).height();
    　　if(scrollTop + windowHeight == scrollHeight&&is_bool){
    　　　　getTopicCommentsList();
    　　}
    });

    //点击评论
    $('.faBu').click(function(){
        $('.zhezhao').show();
        $('.comments-div').animate({top:'0px'},500);
    });

    // 上传图片触发事件
    $('#document-file').change(function(){
        uploadFile();
    });

    //微信jssdk初始化
    doDefault();

    $('.cancel').click(function(){
        $('.comments-div').animate({top:'100%'},500);
        setTimeout(function(){
            $('.zhezhao').hide();
        },499);
    });
    $('.confirm').click(function(){
        if($('.comments-div .comments-textarea textarea').val()==''){
            errorAlert('请填写评论');
            return;
        }
        var load_alert=loadAlert('评论中...');
        //提交评论
        $.ajax({
            type: "post",
            url: "Api/Topic/saveTopicComments",
            data: $('#topic-comments-form').serialize(),
            async: true,
            dataType: 'json',
            success: function(data) {
                setTimeout(function(){
                    closeAlert(load_alert);
                    if (data.status) {
                        var t=JSON.parse(data.v);
                        $('.huaTiChaK-demo .ChaKUser img').attr('src',t.wx_head_img);
                        $('.huaTiChaK-demo .ChaKTextTitle').html(t.name_char);
                        $('.huaTiChaK-demo .topic-comments-content').html(t.content);
                        //图片
                        if(t.img.length>0){
                            var html='';
                            $.each(t.img,function(k1,v1){
                                html+='<img src="'+v1.path+'">'
                            });
                            $('.huaTiChaK-demo .topic-img').html(html).show();
                        }else{
                            $('.huaTiChaK-demo .topic-img').html('').hide();
                        }
                        //20191118新需求，评论提交后不再直接显示，需要后台选择上墙踩能显示
                        // $('.huaTiChaK-box').prepend($('.huaTiChaK-demo').html());  
                        //更新浏览记录与评论数
                        resetRecordNum();

                        $('.cancel').click();
                        //清空表单
                        $('.comments-div .comments-textarea textarea').val('');
                        $('.comments-div .new-img').remove();
                        //图片上传数归0
                        img_count=0;
                    } else {

                    }

                },1000); 
            }
        });
        
    });

    setTopicImgHeight();
    $(window).resize(function(){
        setTopicImgHeight();
    });
})



function getTopicCommentsList() {
    //禁止滚动
    is_bool=false;
    $('.load').show();
    $.ajax({
        type: "post",
        url: "Api/Topic/getTopicCommentsList",
        data: {
            topic_id: $('#topic_id').val(),
            page_no:page_no
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            if (data.status) {
                setTimeout(function(){
                    $('.load').hide();
                    var t = JSON.parse(data.v);
                    $('.search-result lable').eq(0).html(t.count);
                    $.each(t.data, function(k, v) {
                        $('.huaTiChaK-demo .ChaKUser img').attr('src',v.wx_head_img);
                        $('.huaTiChaK-demo .ChaKTextTitle').html(v.name_char);
                        $('.huaTiChaK-demo .topic-comments-content').html(v.content);
                        //图片
                        if(v.img.length>0){
                            var html='';
                            $.each(v.img,function(k1,v1){
                                html+='<img src="'+v1.path+'" onclick="showImages(this);">'
                            });
                            $('.huaTiChaK-demo .topic-img').html(html).show();
                        }else{
                            $('.huaTiChaK-demo .topic-img').html('').hide();
                        }
                        $('.huaTiChaK-box').append($('.huaTiChaK-demo').html());
                    });
                    is_bool=t.have;
                    page_no++;
                    if(!t.have){
                        $('.no-data').show();
                    }
                    setTopicImgHeight();
                },1000);
                // lazyLoad();
                // $(window).scroll();
            } else {

            }
        }
    });
}



var now_type = '';

function uploadDocument(obj) {
    now_type = $(obj).attr('data-type');
    $('#document-file').click();
}

img_count=0;

function uploadFile() {
    var fileObj = document.getElementById("document-file").files; // js 获取文件对象
    if(fileObj.length==0){
        errorAlert('请选择图片');
        return;
    }
    if(img_count>=9){
        errorAlert('最多只能上传9张图片');
        return;
    }
    var formFile = new FormData();
    for (var i = 0; i <fileObj.length; i++) {
        formFile.append("myfile[]", fileObj[i]); //加入文件对象
    }
    var data = formFile;

    $('.document-p .progress-bar').css('width', '0%');
    $('.document-p .p-text').html('已上传（0%）');
    $('.document-p').show();
    $('.add-img').removeAttr('onclick');
    // $('.zhezhao').show();
                    
    img_count++;
    setTimeout(function() {
        $.ajax({
            url: 'Admin/CommonUpload/upload/' + now_type,
            data: data,
            type: "POST",
            dataType: "json",
            cache: false, //上传文件无需缓存
            processData: false, //用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            xhr: xhrOnProgress(function(e) {
                var percent = e.loaded / e.total;
                var now_jindu = (parseFloat(percent) * 100).toFixed(2);
                console.log(now_jindu);
                $('.document-p .progress-bar').css('width', now_jindu + '%');
                $('.document-p .p-text').html('已上传（' + now_jindu + '%）');
                $('.document-p').show();
            }),
            success: function(data) {
                $('.add-img').attr('onclick','uploadDocument(this)');
                $('.document-p .progress-bar').css('width', '100%');
                $('.document-p .p-text').html('已上传（100%）');
                $('.document-p').hide();
                if (data.status) {
                    // alert(now_type);
                    var path=JSON.parse(data.v);
                    var icon=JSON.parse(data.remark);
                    
                    $('.topic-comments-img-demo img').attr('src',path);
                    $('.topic-comments-img-demo .path').val(path);
                    $('.comments-img').append($('.topic-comments-img-demo').html());
                    
                } else {
                    errorAlert(data.msg);
                    img_count--;
                }
            }
        })
    }, 1000);
}

var xhrOnProgress = function(fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
    //使用闭包实现监听绑
    return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
            return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
            xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
    }
}

function delTopicCommentsImg(obj){
    $(obj).parents('.new-img').remove();
}

function addBrowse(){
    $.ajax({
        type: "post",
        url: "Api/Topic/addBrowse",
        data: {
            park_id:$('#park_id').val(),
            topic_id: $('#topic_id').val(),
            openid:$('#openid').val(),
            admin_id:$('#admin_id').val(),
            wx_name:$('#wx_name').val(),
            wx_head_img:$('#wx_head_img').val()
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            resetRecordNum();
        }
    });
}

function resetRecordNum(){
    $.ajax({
        type: "post",
        url: "Api/Topic/getTopic",
        data: {
            park_id:$('#park_id').val(),
            topic_id: $('#topic_id').val()
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            if(data.status){
                var t=JSON.parse(data.v);
                $('.browse-count').html(t.browse_count);
                $('.comments-count').html(t.comments_count);
            }
            else{

            }
        }
    });
}


//获取微信jssdk凭证
function doDefault(successCallBack,errorCallBack) {
    var successCallBack=successCallBack||false; 
    var errorCallBack=errorCallBack||false; 
    $.ajax({
        type: "post",
        url: "CommonApi/CommonWx/getWxJsSdkConfig",
        data: {
            url: window.location.href,
            park_id:$('#park_id').val()
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            if (data.status) {
                var t = JSON.parse(data.v);
                wx.config({
                    beta: true,
                    debug: false,
                    appId: t.appId,
                    timestamp: t.timestamp,
                    nonceStr: t.nonceStr,
                    signature: t.signature,
                    jsApiList: ['checkJsApi',"previewImage"] // 必填，需要使用的JS接口列表
                });
                if(successCallBack){
                    successCallBack();
                }
            } else {
                errorAlert(data.msg);
                if(errorCallBack){
                    errorCallBack();
                }
            }
        }
    });
}


var showImages=function(obj){
    // alert(document.domain);
    var current=$(obj).attr('src');
    if(current.substr(0,7).toLowerCase() == "http://"||current.substr(0,8).toLowerCase() == "https://"){
        var current=current;
    }
    else{
        if(current.substr(0,8).toLowerCase()=='/ueditor'){
            var current='http://'+document.domain+current;
        }
        else if(current.substr(0,1).toLowerCase()=='/'){
            var current=getRootPath()+current;
        }
        else{
            var current=getRootPath()+'/'+current;
        }  
    }
    wx.ready(function() {
        wx.checkJsApi({
            jsApiList: ['previewImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,  
            success: function(res) {
                if (res.checkResult.onMenuShareAppMessage == false) {
                    alert("您的微信版本太低！");
                    return;
                }
            }
        });
        var img=[];
        $(obj).parent().find("img").each(function(){
            if($(this).attr('src').substr(0,7).toLowerCase() == "http://"||$(this).attr('src').substr(0,8).toLowerCase() == "https://"){
                img.push($(this).attr('src'));
            }
            else{
                if($(this).attr('src').substr(0,8).toLowerCase()=='/ueditor'){
                    img.push('http://'+document.domain+$(this).attr('src'));
                }
                else if($(this).attr('src').substr(0,1).toLowerCase()=='/'){
                    img.push(getRootPath()+$(this).attr('src'));
                }
                else{
                    img.push(getRootPath()+'/'+$(this).attr('src'));
                }    
            } 
        });
        wx.previewImage({
            current: current, // 当前显示图片的http链接
            urls: img // 需要预览的图片http链接列表
        });
    });
}

function setTopicImgHeight(){
    $('.topic-img img').each(function(){
        $(this).height($(this).width());
    });
}